package com.example.javapoint.sync.block;

/**
 * synchronized 同步代码块
 */
class NeedBlock {
    public void print(int n) {
        synchronized (this) {
            for (int i = 1; i < 10; i++) {
                System.out.println( n * i);
                try {
                    Thread.sleep(400);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}


class MyThread1 extends Thread {
    NeedBlock block;

    public MyThread1(NeedBlock block){
        this.block = block;
    }

    @Override
    public void run() {
        block.print(10);
    }
}

class MyThread2 extends Thread {
    NeedBlock block;

    public MyThread2(NeedBlock block){
        this.block = block;
    }

    @Override
    public void run() {
        block.print(100);
    }
}

public class TestSyncBlock1 {
    public static void main(String[] args) {
        NeedBlock needBlock = new NeedBlock();
        MyThread1 myThread1 = new MyThread1(needBlock);
        MyThread2 myThread2 = new MyThread2(needBlock);

        myThread1.start();
        myThread2.start();

    }
}
